package com.zhx.app;

import com.zhx.app.jwt.JwtTokenEnhancer;
import com.zhx.core.common.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * 配置token存储的地方
 *
 * ConditionalOnProperty
 *
 * @author zhx
 * @create 2017-12-14 16:16
 **/
@Configuration
public class TokenStoreConfig {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    @ConditionalOnProperty(prefix = "zhx.security.oAuth2Properties",name = "storeType",havingValue ="redis")
    public TokenStore redisTokenStore(){
        return new RedisTokenStore(redisConnectionFactory);
    }

    @Configuration
    @ConditionalOnProperty(prefix = "zhx.security.oAuth2Properties",name = "storeType",havingValue ="jwt",matchIfMissing = true)
    public static class JWTTokenConfig{

        @Autowired
        private SecurityProperties securityProperties;

        @Bean
        public  TokenStore jWTokenStore(){
            return new JwtTokenStore(jwtAccessTokenConverter());
        }

        /**
         * 主要作用是设置秘钥
         * 秘钥是jwt秘钥的唯一
         * @return
         */
        @Bean
        public JwtAccessTokenConverter jwtAccessTokenConverter(){
            JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
            jwtAccessTokenConverter.setSigningKey(securityProperties.getoAuth2Properties().getSignKey());
            return jwtAccessTokenConverter;
        }

        /**
         * 可以在jwt中设置自定义的字段的处理bean
         * @return
         */
        @Bean
        @ConditionalOnBean(TokenEnhancer.class)
        public TokenEnhancer jwtTokenEnhancer(){
            return new JwtTokenEnhancer();
        }
    }
}
